/*
 *  Map Manager
 *  Manage interface between Leaflet and ItemManager
 */

function MM()
{
	
	// initialazing map
	var layer_tile = L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
				maxZoom: 18,
				attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery Â© <a href="http://cloudmade.com">CloudMade</a>'
				});
	
	var registrationLayer = new L.LayerGroup(); // temp marker where you add thing
	// L.LayerGroup(); if clustering is off
	var layer_items = new L.MarkerClusterGroup(); // collect all items markers
	var layer_item = new L.LayerGroup(); // collect one item's marker
	
	// point to calculate distance
	var distanceFrom = null;
	
	// initialize map object
	var map = new L.Map('map', {
		// center in Brussels
	    center: new L.LatLng(39.90973623453719, -93.69140625),
	    zoom: 3,
	    layers: [layer_tile, registrationLayer, layer_items, layer_item]
		// registrationLayer : marker for the object added
		// markersGroup : for the groups
		// items : for all items that are erased after each move
		// item : for one item that won't be erase after each move
		});

	// display items on map;
	//MM.prototype.displayOnMap();
	
	console.log('MM initialized');
	
	var page = null;
	
	/*
	 *  PUBLIC
	 *  Change the current page value
	 */
	this.set_page = function(newPage)
	{
		page = newPage;
		onPageChange();
	};
	
	this.set_distanceFrom = function(newDistanceFrom)
	{
		distanceFrom = newDistanceFrom;
	};
	
	this.clearLayer_items = function()
	{
		console.log('clear');
		layer_items.clearLayers();
	};
	
	this.push = function(item)
	{
		// create location object
		item.latlng = new L.LatLng(item.lat, item.lng);
		// create marker object
		var marker = new L.Marker(item.latlng);
		// message
		var msg = '<div id="thing_popup">'
		+ '<img src="" />'
		+ '<strong>' + item.title + '</strong></br>'
		+ item.description + '</br>'
		+ 'by ' + item.username + '<div/>';
		// bind message with marker
	    marker.bindPopup(msg);
	    
	    layer_items.addLayer(marker);
	    // link marker with the item
	    item.setMarker(marker);
	};
	
	this.getPrecision = function()
	{
		var distance = 10000;
		switch(map.getZoom())
		{
			case 18: distance=200; break;
			case 17: distance=200; break;
			case 16: distance=500; break;
			case 15: distance=2000; break;
			case 14: distance=8000; break;
			case 13: distance=32000; break;
			case 12: distance=128000; break;
			case 11: distance=512000; break;
			case 10: distance=2048000; break;
			default: distance=10000; break;
		}
		return distance;
	};
	
	/*
	 *  Create an object
	 *  
	 */
	
	registrationMarker = new L.Marker([0,0]);
	
	registrationMarker.options.draggable = true;
	var firstClick = true;
	function onMapClick(e)
	{
		var markerLocation = new L.LatLng(e.latlng.lat, e.latlng.lng);
		registrationMarker.setLatLng(markerLocation);
	    registrationLayer.clearLayers();
	    registrationLayer.addLayer(registrationMarker);	
		var msg = 'Your object will be added here! You can still move it';
				
		registrationMarker.bindPopup(msg, {closeButton: false}).openPopup();
		
		if(firstClick)
		{
			firstClick = false;
			$('#message').html('<img class="center" src="assets/img/ajax-loader.gif">');
		    $('#message').load('pages/view_part/register');
		}
	}
	
	this.get_registrationMarker = function()
	{
		return registrationMarker;
	};
	
	/*
	 *  Others
	 * 
	 */
	
	function onMoveEnd(e)
	{
		console.log('onMoveEnd');
	
		switch(page)
		{
			case 'items' :
				// create bounds array
				var bounds = [];
				// get map bounds
				bounds[0] = map.getBounds().getNorthWest().lat;
				bounds[1] = map.getBounds().getNorthWest().lng;
				bounds[2] = map.getBounds().getSouthEast().lat;
				bounds[3] = map.getBounds().getSouthEast().lng;
				
				// get items
				IMC.init_display('bounds', null, bounds);
			break;
			case 'user' :
				var uid = IMC.get_uid();
				
				// display the items of the user
				IMC.init_display('user', uid, null);
			break;
		}
	}
	
	this.refresh = function()
	{
		onMoveEnd(null);
	};
	
	this.init_create = function()
	{
		map.addEventListener('click', onMapClick);
	};
	
	this.cancel_create = function()
	{
		registrationMarker.closePopup();
	    registrationLayer.clearLayers();
	    firstClick = true;
		map.removeEventListener('click', onMapClick);
	};
	
	function init_onMoveEnd()
	{
		map.addEventListener('moveend', onMoveEnd);
	}
	
	function cancel_onMoveEnd()
	{
		map.removeEventListener('moveend', onMoveEnd);
	}
	
	function onPageChange()
	{
		init_onMoveEnd();
	}
	
	this.locate = function(mode, lat, lng, id)
	{
		console.log('map moved in mode : '+mode);
		switch(mode)
		{
			// locate an item by id
			case 'id' :
				var items = IM.getItems();
				var latLng = [items[id].lat, items[id].lng];
				map.panTo(latLng);
			break;
			// locate from given coordinates
			case 'coord' :
				var latLng = [lat, lng];
				map.setZoom(10);
				map.panTo(latLng);
			break;
			// localizing from ip
			case 'here' :
				map.locate({setView: true, maxZoom: 16}); // setView: true, shorcut to ask to locate the user
			break;
		}
	};
	
	function location_search(string)
	{
		//alert(string);
		var bounds = map.getBounds();
		NW = bounds.getNorthWest();
		NWlat = bounds.getNorthWest().lat;
		NWlng = bounds.getNorthWest().lng;
		SElat = bounds.getSouthEast().lat;
		SElng = bounds.getSouthEast().lng;
		bounds = new Array(NWlat, NWlng, SElat, SElng);
		
		$.ajax({
			url: 'http://open.mapquestapi.com/geocoding/v1/address',
			dataType: 'jsonp',
			crossDomain: true,
			data: {
				location : string,
				boundingBox: {
					ul:{
						lat:NWlat,
						lng:NWlng},
					lr:{
						lat:SElat,
						lng:SElng}
					},
				maxResults : 1
			},
			timeout: 3000,
			success: function(data)
			{
				lat = data.results[0].locations[0].latLng.lat;
				lng = data.results[0].locations[0].latLng.lng;
				latLng = [lat, lng];
				map.panTo(latLng);
				display_alert('location found', '#alert_area', 'success');
			},
	        error: function() { display_alert('connexion problem', '#alert_area', 'error'); }
		});
	}
	
	/*
	 *  get the center to calculate the distance
	 */
	this.getCenter = function()
	{
		var center = null;
		
		switch(distanceFrom)
		{
			// distance from the map center
			case 'here' :
				center = map.getCenter();
			break;
			// distance from registred user location
			case 'user' : break;
		}
		
		console.log('center '+center + distanceFrom);
		
		return center;
	};
	
	
	/*switch('here')
	{
		case 'here': MM.locate(); break;
	}*/
};

console.log('MM loaded');